#coding:utf-8
# from db_base.sqlprocess import connDB
import app_setting
import json 
import requests
from mg_config import yz_log


def wx_accesstoken(r_cli):
	wx_accesstoken = r_cli.get("wx:accesstoken")
	if wx_accesstoken:
		return wx_accesstoken 
	try:
		url =  app_setting.WX_ACCESS_URL % (app_setting.WX_APPID, app_setting.WX_SECRET)
		res = requests.get(url,headers={'Connection':'close'})
		res = res.json()
		yz_log.info(res)
		if res.get("access_token"):
			access_token = res.get("access_token")
			r_cli.set("wx:accesstoken",access_token)
			r_cli.expire("wx:accesstoken",6000)
			return access_token
	except Exception as e:
		yz_log.error(str(e))
		return None


def getjsapiticket(r_cli, access_token):
	jsapi_ticket = r_cli.get("wx:jsapi_ticket")
	if jsapi_ticket:
		return jsapi_ticket


	try:
		res = requests.get(app_setting.WX_JSAPI_TIKET % access_token )
		res = res.json()
		yz_log.info(res)
		if res.get("ticket"):
			jsapi_ticket = str(res.get("ticket"))
			r_cli.set("wx:jsapi_ticket",jsapi_ticket)
			r_cli.expire("wx:jsapi_ticket",6000)
			return jsapi_ticket
	except Exception as e:
		yz_log.error(str(e))
		return None